import MvnRepoLock
import MvnRepoUnLock
import ConfUpdateLock
import ConfUpdateUnLock
import Sonarqube
def call(String branch, Map conf, String gitUrl) {
    env.BUILD_TIME = sh(returnStdout: true, script: "(date '+%Y.%m.%d.%H%M%S')").trim()
    env.BUILD_DATE = sh(returnStdout: true, script: "(date '+%Y.%m.%d')").trim()
    pipeline {
        agent any
        stages {
            //步骤设置
            stage('拉取git仓库代码') {
                steps {
                    dir('code') {
                        git branch: branch, credentialsId: conf.gitCredentialsId, url: gitUrl
                    }
                    echo '拉取git仓库代码-SUCCESS'
                }
            }

            stage('通过maven构建项目') {
                steps {
                    dir('code') {
                        script {
                            env.COMMIT_ID = sh(returnStdout: true, script: "git rev-parse --short HEAD").trim()
                            env.BUILD_VERSION = "${env.BUILD_TIME}-${env.COMMIT_ID}"
                            echo "env.BUILD_VERSION=${env.BUILD_VERSION}"
                            mrl = MvnRepoLock()
                            if (!mrl) {
                                error 'get mvn repo lock failure'
                            }
                            if (null != conf.dotDelRepo && conf.dotDelRepo.contains(env.PROJECT_NAME)) {
                                echo 'dot del repo'
                            } else {
                                sh """rm -rf /usr/local/apache-maven-3.9.6/repo/com/xxx"""
                            }
                            sh """/usr/local/apache-maven-3.9.6/bin/mvn package '-Dmaven.test.skip=true'"""
                            MvnRepoUnLock()
                        }
                    }
                    echo '通过maven构建项目-SUCCESS'
                }
            }

            stage('sonarqube') {
                steps {
                    dir('code') {
                        script {
                            // 一天只执行一次
                            if (null != conf.sonarqube && conf.sonarqube.contains(env.PROJECT_NAME) && Sonarqube(env.PROJECT_NAME, env.BUILD_DATE)) {
                                sh """/usr/local/apache-maven-3.9.6/bin/mvn clean verify sonar:sonar -Dsonar.projectKey=xxx -Dsonar.projectName='xxx' -Dsonar.host.url=http://xxx:6004 -Dsonar.token=sqp_61c4d7d4417a0516434aa5c6dd9f4fc154113b6a"""
                            } else {
                                echo 'no sonarqube step'
                            }
                        }
                    }
                    echo 'sonarqube-SUCCESS'
                }
            }

            stage('通过docker制作自定义镜像') {
                steps {
                    dir('code') {
                        sh """find -name "${env.PROJECT_NAME}*.jar" -exec cp -a {} app.jar \\;"""
                        sh """docker build --build-arg APP_NAME=${env.PROJECT_NAME} --build-arg APP_VERSION=${env.BUILD_VERSION} -t ${env.PROJECT_NAME}:${env.BUILD_VERSION} ."""
                    }
                    echo '推送到Docker仓库-SUCCESS'
                }
            }

            stage('将自定义镜像推送到仓库中') {
                steps {
                    dir('code') {
                        sh """docker login --username=admin --password=Harbor12345 registry.tt.com
/usr/bin/docker tag ${env.PROJECT_NAME}:${env.BUILD_VERSION} registry.tt.com/xxx-${env.ENV}/${env.PROJECT_NAME}:${env.BUILD_VERSION}
/usr/bin/docker push registry.tt.com/xxx-${env.ENV}/${env.PROJECT_NAME}:${env.BUILD_VERSION}
/usr/bin/docker rmi ${env.PROJECT_NAME}:${env.BUILD_VERSION}
/usr/bin/docker rmi registry.tt.com/xxx-${env.ENV}/${env.PROJECT_NAME}:${env.BUILD_VERSION}"""
                    }
                    echo '推送到仓库-SUCCESS'
                }
            }

            stage('pull conf') {
                steps {
                    dir('conf') {
                        git branch: branch, credentialsId: conf.confCredentialsId, url: conf.confUrl
                    }
                    echo 'pull conf-SUCCESS'
                }
            }

            stage('update conf') {
                steps {
                    dir('conf') {
                        script {
                            cul = ConfUpdateLock()
                            if (!cul) {
                                error 'get conf update lock failure'
                            }
                            sh 'chmod -R 775 script.sh'
                            sh """./script.sh ${env.BUILD_VERSION} ${env.PROJECT_NAME}/${env.PROJECT_NAME}-${env.ENV}.yaml"""
                            sh 'git commit -a -m "1.update version"'
                            sh """git push origin ${branch}"""
                            ConfUpdateUnLock()
                        }
                    }
                    echo 'update conf-SUCCESS'
                }
            }

            stage('K8S部署') {
                steps {
                    dir("""conf/${env.PROJECT_NAME}""") {
                        sshPublisher(publishers: [sshPublisherDesc(configName: 'k8s', transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: '', execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: '', remoteDirectorySDF: false, removePrefix: '', sourceFiles: """${env.PROJECT_NAME}-${env.ENV}.yaml""")], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false)])
                    }
                    sshPublisher(publishers: [sshPublisherDesc(configName: 'k8s', transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: """sudo kubectl apply -f /usr/local/${env.PROJECT_NAME}-${env.ENV}.yaml""", execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: '', remoteDirectorySDF: false, removePrefix: '', sourceFiles: '')], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: true)])
                    echo 'K8S部署-SUCCESS'
                }
            }

            stage('等待k8s滚动升级完成') {
                steps {
                    sshPublisher(publishers: [sshPublisherDesc(configName: 'k8s', transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: """sudo kubectl rollout status deployment/${env.PROJECT_NAME}-${env.ENV}-pod -n xxx-${env.ENV}""", execTimeout: 600000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: '', remoteDirectorySDF: false, removePrefix: '', sourceFiles: '')], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: true)])
                    echo 'k8s滚动升级完成-SUCCESS'
                }
            }

            stage('获取版本号') {
                steps {
                    sshPublisher(publishers: [sshPublisherDesc(configName: 'k8s', transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: """sh /usr/local/pod_version.sh ${env.PROJECT_NAME}-${env.ENV}-service xxx-${env.ENV}""", execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: '', remoteDirectorySDF: false, removePrefix: '', sourceFiles: '')], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: true)])
                    echo '获取版本号-SUCCESS'
                }
            }
        }
        post {
            always {
                script {
                    MvnRepoUnLock()
                    ConfUpdateUnLock()
                }
                cleanWs()
                echo 'the pipeline script end'
            }
        }
    }
}